import pickle
import time
from concurrent.futures import ThreadPoolExecutor
from functools import reduce
import os

import schedule

import config
import tool
from thread.test import strat


def start_mail():

    aList = os.getcwd().split('\\')[:-1]
    path = (reduce(lambda x, y: x + '\\' + y, aList))
    mail_file=[os.path.join(path,name) for name in os.listdir(path) if name.find('_' + os.path.basename(config.path_163)) > -1]
    f = open(tool.TOOL.getPropath()+'/cookies_163.obj', 'wb')
    if len(mail_file)  < config.thead_max:
        thread_number=len(mail_file)
    else:
        thread_number=config.thead_max

    executor=ThreadPoolExecutor(thread_number)
    print('实际开通线程数为：%d'%thread_number)
    text_num=int(len(mail_file)/thread_number)

    index=0
    end=text_num
    treaders=[]
    for i in range(thread_number):
        result =mail_file[index:end]
        if len(result) == 0 :
            break
        index=end
        end=end+text_num
        treaders.append(executor.submit(strat, result))

    try:
        [r.result() for r in treaders]
    except:
        pass

    print(config.cookies_163)
    pickle.dump(config.cookies_163, f)
    f.close()




def job():
    tool.TOOL.create_mail_text()
    start_mail()
    f = open(tool.TOOL.getPropath() + '/cookies_163.obj', 'rb')
    d = pickle.load(f)
    f.close()
    print('成功登陆的邮箱%d个' % len(d))

schedule.every().day.at("23:00").do(job)
def start():
    print('邮箱定时成功！')
    while True:
        schedule.run_pending()
        time.sleep(1)


if __name__ == '__main__':
    start()